package com.lagou.cl.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


public class MyClassLoader extends ClassLoader {

	private String path;

	public MyClassLoader(String path) {
		this.path = path;
	}

	/**
	 * 查询类
	 *
	 * @param name 类的全路径
	 */
	@Override
	protected Class<?> findClass(String name) {
		byte[] data = loadClassData();
		assert data != null;
		return defineClass(name, data, 0, data.length);
	}

	/**
	 * 将.class文件读入内存中，并且以字节数形式返回
	 */
	private byte[] loadClassData() {
		File file = new File(path);
		if (file.exists()) {
			FileInputStream in = null;
			ByteArrayOutputStream out = null;
			try {
				in = new FileInputStream(file);
				out = new ByteArrayOutputStream();

				byte[] buffer = new byte[1024];
				int size = 0;
				while ((size = in.read(buffer)) != -1) {
					out.write(buffer, 0, size);
				}

			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					assert in != null;
					in.close();
				} catch (IOException e) {

					e.printStackTrace();
				}
			}
			return out.toByteArray();
		} else {
			return null;
		}
	}

}



